// pages/address/address.js
Page({
  data: {
    globalData: getApp().globalData,
    addresses: []
  },

  onLoad(options) {
    this.getAddresses()
  },
  onShow() {
    if(wx.getStorageSync('user') == '') {
      wx.showModal({
        title: '提示',
        content: '请登录查看',
        complete: (res) => {
          if (res.confirm) {
            wx.navigateTo({url: '/pages/login/login',})
          } else if (res.cancel) {
            wx.navigateBack()
          }
        }
      })
    }
  },

  getAddresses() {
    let that = this
    wx.request({
      url: that.data.globalData.server + '/address/query',
      method: 'GET',
      data: {userId: wx.getStorageSync('user').userId},
      success(res) {
        that.setData({
          addresses: res.data.data
        })
      }
    })
  },
  editDefault(e) {
    let address = e.currentTarget.dataset.item
    let that = this
    wx.request({
      url: that.data.globalData.server + '/address/default',
      method: 'PUT',
      data: {
        addressId: address.addressId,
        userId: address.userId,
        isDefault: true
      },
      success(res) {
        that.getAddresses()
      }
    })
  },
  toAddAddr(e) {
    wx.navigateTo({url: '/pages/addAddr/addAddr?id=' + e.currentTarget.dataset.id})
  },
  delAddress(e) {
    wx.showModal({
      title: '警告',
      content: '确认删除地址吗？',
      complete: (res) => {
        if (res.confirm) {
          let id = e.currentTarget.dataset.id
          let that = this
          wx.request({
            url: that.data.globalData.server + '/address/' + id,
            method: 'DELETE',
            success(res) {
              that.getAddresses()
            }
          })
        }
      }
    })
  }

})